package handler

import (
	"github.com/gin-gonic/gin"
	"gorm-demo/model/request"
	"gorm-demo/service/user"
	"gorm-demo/utils"
	"net/http"
)

// Login /*
func Login(context *gin.Context) {
	var loginVo request.LoginVo
	if err := context.ShouldBindJSON(&loginVo); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": "请求格式错误"})
		return
	}
	//	登录逻辑
	token, err := user.LoginService(loginVo.Username, loginVo.Password)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	//保存token
	context.Set(token, user.GetPermissionByToken(token))
	context.JSON(http.StatusOK, gin.H{"token": token})
}

// UserPermissionTree  获取权限树/*
func UserPermissionTree(context *gin.Context) {
	token := context.GetHeader("authorization")
	id, err := utils.GetUserId(token)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": "登录过期"})
	}
	tree := user.GetPermissionTreeByUid(id)
	context.JSON(http.StatusOK, gin.H{"roles": tree})
}

func Register(context *gin.Context) {
	var uservo request.UsernameVo
	if err := context.ShouldBindJSON(&uservo); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	encode, err2 := utils.Encode(uservo.Password)
	if err2 != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": "注册失败请重试"})
		return
	}
	err := user.AddUser(uservo.Username, encode)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	context.JSON(http.StatusOK, gin.H{"msg": "注册成功!"})
}
func Logout(context *gin.Context) {
}
